// 用户数据模块
import {
	router
} from '@/common/router/index.js'
import {
	tokenLogout
} from "@/common/apis/login.js"
const TOKEN = uni.getStorageSync("token") || "";

export const state = {
	// 前端token
	token: TOKEN,
	countdown: 0, // 倒计时时间，例如5分钟
	timer: null,
	shadowShow: false,
	userinfo: {},
	cameraShot: true
}

export const actions = {
	// 登录过期 重新登录
	reLogin({state,commit}, info) {
		tokenLogout({
			token: state.token
		}).then(res => {
			console.log(res, "this is logout token")
		})
		commit('setStateAttr', {
			key: 'token',
			val: ''
		})
		uni.setStorageSync("token", '');
		//清除定时器
		commit("CLEAR_TIMER")
		//停止倒计时
		commit("STOP_COUNTDOWN")
		//取消遮罩层
		commit('setStateAttr', {
			key: 'shadowShow',
			val: false
		});
		uni.clearStorageSync();
		uni.redirectTo({
			url: '/pages/index/index'
		});
	},
	setToken({
		commit
	}, token) {
		uni.setStorageSync("token", token);
		commit('setStateAttr', {
			key: 'token',
			val: token
		})
	},
	startCountdown({
		commit,
		state,
		dispatch
	}) {
		//清除定时器
		commit("CLEAR_TIMER")
		//重置计数器
		commit('RESET_COUNTDOWN');
		//取消遮罩层
		commit('setStateAttr', {
			key: 'shadowShow',
			val: false
		});
		//设置循环器
		commit('setStateAttr', {
			key: 'timer',
			val: setInterval(() => {

				if (state.countdown <= 0) {
					console.log('倒计时结束');
					dispatch('reLogin');
				} else {

					if (state.countdown <= 3000) {

						//显示遮罩层
						commit('setStateAttr', {
							key: 'shadowShow',
							val: true
						});
					}
					commit('DECREMENT_COUNTDOWN');
				}
			}, 1000)
		});
	},
	refreshCountDown({
		commit,
		state
	}) {
		commit('RESET_COUNTDOWN');
	},
	setUserInfo({
		commit
	}, userinfo) {
		commit('setStateAttr', {
			key: 'userinfo',
			val: userinfo
		})
	},
	setCameraShot( {commit}, state) {
		commit('setStateAttr', {
			key: 'cameraShot',
			val: state
		})
	},
}

export const mutations = {
	//更新state数据
	setStateAttr(state, param) {
		if (param instanceof Array) {
			for (let item of param) {
				state[item.key] = item.val;
			}
		} else {
			state[param.key] = param.val;
		}
	},
	RESET_COUNTDOWN(state) {
		state.shadowShow = false
		state.countdown = 40 * 1000;
	},
	DECREMENT_COUNTDOWN(state) {
		state.countdown -= 1000; // 每秒递减
	},
	STOP_COUNTDOWN(state) {
		state.countdown = 0
	},
	CLEAR_TIMER(state) {
		console.log("this is clear timer")
		clearInterval(state.timer);
		state.timer = null
	},
	SET_CAMERA_SHOT(state,param){
		state.cameraShot = param
	}
}

export const getters = {
	// 用户是否登录
	hasLogin: state => {
		if (state.token) {
			return true;
		} else {
			return false
		}
	}
}